window.onload = () => {
    let pagenum = 0;
    let scroll_times;
    //! 判断用户名
    if (localStorage.getItem('uid')) {
        $('#uname').html(`<a href="javascript:;">${localStorage.getItem('username')}</a>`)
        $('.portrait-right a:eq(0) span').text(localStorage.getItem('username'))
        $('.portrait-right p').html(`<a href="./index.html" class="quit">退出</a>`)
    }

    // !点击事件
    $('.quit').on('click', () => {
        localStorage.removeItem('username')
        localStorage.removeItem('password')
        localStorage.removeItem('uid')
        localStorage.removeItem('token')
    });

    // ! 顶部广告
    topBanner()

    function topBanner() {
        $('#J_promotional-top .del').click(() => {
            $('#J_promotional-top').css('display', 'none')
        })
    }

    // !监听滚动条 事件
    scroll()

    function scroll() {
        window.onscroll = function() {
            // 滚动条 网页被卷去的高
            let gdt = document.documentElement.scrollTop;
            // 网页正文全文高
            let ymg = document.documentElement.scrollHeight;
            // 网页可见区域高
            let ks = document.documentElement.clientHeight;
            let Lis = document.querySelectorAll('.elevator ul li');
            // !加载更多
            if (gdt >= ymg - ks - 800) {
                clearTimeout(scroll_times)
                scroll_times = setTimeout(() => {
                    pagenum++
                    // 列表
                    p_list()
                }, 500)
            }
            // !吸顶
            console.log(gdt);
            if (gdt > 600) {
                $('#search-wrap').css('display', 'block')
            } else {
                $('#search-wrap').css('display', 'none')
            }
            // !电梯换色
            if (gdt > 600) {
                $('.elevator').show(300)
            } else {
                $('.elevator').hide(300)
            }
            if (gdt >= 660) {
                $('.elevator ul li a').css('color', '#666');
                $('.elevator ul li a').eq(0).css('color', 'red')
            }
            if (gdt >= 950) {
                $('.elevator ul li a').css('color', '#666');
                $('.elevator ul li a').eq(1).css('color', 'red')
            }
            if (gdt >= 1290) {
                $('.elevator ul li a').css('color', '#666');
                $('.elevator ul li a').eq(2).css('color', 'red')
            }
            if (gdt >= 1594) {
                $('.elevator ul li a').css('color', '#666');
                $('.elevator ul li a').eq(3).css('color', 'red')
            }
        }
    }
    // !电梯点击事件
    Elevator()

    function Elevator() {
        $('#back-top').on('click', () => {
            $('html, body').animate({ scrollTop: '0px' }, 400, 'swing')
        })
        $('#back-seckill').on('click', () => {
            $('html, body').animate({ scrollTop: '660px' }, 400, 'swing')
        })
        $('#back-every').on('click', () => {
            $('html, body').animate({ scrollTop: '950px' }, 400, 'swing')
        })
        $('#back-nice').on('click', () => {
            $('html, body').animate({ scrollTop: '1290px' }, 400, 'swing')
        })
        $('#back-recommend').on('click', () => {
            $('html, body').animate({ scrollTop: '1594px' }, 400, 'swing')
        })
    }

    // !大轮播图
    bigSlideshow()

    function bigSlideshow() {
        let bigSlideshowData = [{ img: '1.jpg.webp' }, { img: '2.jpg.webp' }, { img: '3.jpg.webp' }, { img: '4.jpg.webp' }, { img: '5.jpg.webp' }, { img: '6.jpg.webp' }];
        let str = bigSlideshowData.map((arr) => {
            return `
            <li>
             <img src="../img/big-slideshow/${arr.img}" alt="">
            </li>`
        });
        $('.big-slideshow ul').html(str);
        let index = 0;
        let flag = true;
        // ! 创建 ol 中的 li
        $('.big-slideshow ul>li').each((i, v) => {
            $('.big-slideshow ol').first().append(`<li index="${i}"></li>`)
        });
        //! 给第一个li添加样式
        $('.big-slideshow ol>li').eq(0).addClass('select-li');
        // ! 右边按键 添加点击事件
        $('.big-slideshow a').eq(1).on('click', () => {
            if (flag) {
                flag = false;
                // ul.children[index].style.opacity = '0' // 当前项 隐藏
                $('.big-slideshow ul>li').eq(index).animate({ opacity: 0 }, 500, () => {
                    flag = true
                })
                index++ //加一项
                if (index == $('.big-slideshow ul>li').length) { //判断是否为最后项
                    index = 0
                }
                // ul.children[index].style.opacity = '1'  //当前项加一项 显示
                $('.big-slideshow ul>li').eq(index).animate({ opacity: 1 }, 500, () => {
                    flag = true
                });
                // ol 与 按钮相关联
                $('.big-slideshow ol>li').removeClass('select-li')
                $('.big-slideshow ol>li').eq(index).addClass('select-li')
            }
        });
        // ! 左边按键 添加点击事件
        $('.big-slideshow a').eq(0).on('click', () => {
            if (flag) {
                flag = false;
                $('.big-slideshow ul>li').eq(index).animate({ opacity: 0 }, 500, () => {
                    flag = true
                });
                index--
                if (index < 0) {
                    index = $('.big-slideshow ul>li').length - 1
                }
                $('.big-slideshow ul>li').eq(index).animate({ opacity: 1 }, 500, () => {
                    flag = true
                });
                // ol 与 按钮相关联
                $('.big-slideshow ol>li').removeClass('select-li');
                $('.big-slideshow ol>li').eq(index).addClass('select-li');
            }
        });
        // ! 左边按键 添加点击事件
        $('.big-slideshow a').eq(0).on('click', () => {
            if (flag) {
                flag = false;
                $('.big-slideshow ul>li').eq(index).animate({ opacity: 0 }, 500, () => {
                    flag = true
                });
                index--
                if (index < 0) {
                    index = $('.big-slideshow ul>li').length - 1
                };
                $('.big-slideshow ul>li').eq(index).animate({ opacity: 1 }, 500, () => {
                    flag = true
                });
                // ol 与 按钮相关联
                $('.big-slideshow ol>li').removeClass('select-li');
                $('.big-slideshow ol>li').eq(index).addClass('select-li');
            }
        });
        //! 自动点击
        let time = setInterval(() => {
            $('.big-slideshow a').eq(1).trigger('click')
        }, 1500);
        //!鼠标 划入 划出
        $('.big-slideshow').hover(() => {
            clearInterval(time)
        }, () => {
            time = setInterval(() => {
                $('.big-slideshow a').eq(1).trigger('click')
            }, 2000)
        })
    }
    // !倒计时
    // DJS()

    // function DJS() {
    // var span = document.querySelectorAll('.time span');
    // // 结束时间
    // var star = new Date('12 31 2021 00:00:00')
    // setInterval(() {
    //     // 现在的时间
    //     let now = new Date();
    //     let t = star - now;
    //     let hour = parseInt(t / 1000 / 60 / 60); // 时
    //     hour = toString(hour);
    //     let minute = parseInt(t / 1000 / 60 % 60); // 分
    //     minute = toString(minute);
    //     let sec = parseInt(t / 1000 % 60); // 秒
    //     sec = toString(sec);
    //     span[0].innerHTML = hour; //时
    //     span[1].innerHTML = minute; //分
    //     span[2].innerHTML = sec; //秒
    // }, 1000);
    // //个位数前加0
    // function toString(unit) {
    //     unit += "";
    //     if (unit.length < 2) {
    //         unit = "0" + unit;
    //     }
    //     return unit;
    // }

    // }
    DJS()

    function DJS() {
        setInterval(() => {
            let data = new Date().getDate()
            data = data < 10 ? '0' + data : +data
            let times = +new Date(`2023-1-${data} 24:00`) - Date.now()
            let s = parseInt(times / 1000 % 60)
            let m = parseInt(times / 1000 / 60 % 60)
            let h = parseInt(times / 1000 / 60 / 60 / 60)
            h = h < 10 ? '0' + h : +h
            m = m < 10 ? '0' + m : +m
            s = s < 10 ? '0' + s : +s
            $('#seckill .time span').eq(0).text(h)
            $('#seckill .time span').eq(1).text(m)
            $('#seckill .time span').eq(2).text(s)
        }, 1000);
    }

    // !分组轮播 四
    groupSlideshow()

    function groupSlideshow() {
        let groupSlideshowData = [{
                img: '01-1.webp',
                pname: `华为 HUAWEI P40 Pro+ 麒麟990 5G SoC芯片 5000万超感知徕卡五摄 100倍双目变焦 8GB+256GB陶瓷白全网通5G`,
                price: '7958.00',
                delPrice: '7988.00',
            },
            {
                img: '01-2.webp',
                pname: `农夫山泉 NFC果汁饮料 100%NFC橙汁300ml*24瓶 整箱装`,
                price: '142.00',
                delPrice: '168.00',
            },
            {
                img: '01-3.webp',
                pname: `鹿客(LOOCK) 指纹锁防盗门锁 全自动推拉S30高配版指纹锁智能锁电子密码锁 免费安装 S30高配版（内含蓝牙网关）`,
                price: '1999.00',
                delPrice: '2999.00',
            },
            {
                img: '01-4.webp',
                pname: `年货节 春节 送礼康新牧场内蒙古草原酱牛肉牛肉熟食五香味牛腱子酱牛肉健身款 酱牛肉五香味150g*3`,
                price: ' 56.90',
                delPrice: '108.00',
            },
            {
                img: '01-5.webp',
                pname: `美国USCAMEL双筒望远镜高倍高清视户外寻蜂旅游观景军工演唱会手机拍照用微光夜视 军绿色10*42超清款`,
                price: '299.00',
                delPrice: '698.00',
            },
            {
                img: '01-6.webp',
                pname: `Insta360 ONE R（双镜头版) 防抖全景运动相机 旅行Vlog口袋相机 摄像机 智能数码相机 骑行滑雪摩托车潜水`,
                price: '2718.00',
                delPrice: '3198.00',
            },
            {
                img: '01-7.webp',
                pname: `【新年请好运，送礼送吉祥】大号和田玉吊坠守护神本命佛玉观音笑佛弥勒佛貔貅玉牌本命年生肖牛虚空藏菩萨 属牛/虎守护神-虚空藏菩萨`,
                price: '496.00',
                delPrice: '1060.00',
            },
            {
                img: '01-8.webp',
                pname: `阿玛尼（Emporio Armani)手表 女表 简约皮带石英表女士手表 AR11199樱花粉`,
                price: '999.00',
                delPrice: '1890.00',
            },
            {
                img: '01-9.webp',
                pname: `南极人儿童卫衣男童女童秋装宝宝卫衣圆领套头上衣泰迪熊IP定制 工程师-中国红（新） 100`,
                price: '59.90',
                delPrice: '139.80',
            },
            {
                img: '11-1.webp',
                pname: '户外年货节秒杀',
                price: '1800.80',
                delPrice: '2700.80',
            },
            {
                img: '11-2.webp',
                pname: '5G手机',
                price: '2800.80',
                delPrice: '3500.80',
            },
            {
                img: '11-3.webp',
                pname: '乐灵珠宝 黄金生肖牛金币金钞足金牛年十二生肖贺岁纪念币福袋牛红包新年压岁钱春节送礼投资收藏XYBJ026-1',
                price: '99.00',
                delPrice: '139.00',
            }
        ]
        let str = groupSlideshowData.map(arr => {
            return `
                <li>
                    <a href="javascript:;">
                        <div class="top">
                            <img src="../img/seckill-img/group-img/${arr.img}" alt="">
                        </div>
                        <h6 title="${arr.pname}">${arr.pname}</h6>
                        <div class="bom">
                            <span><i>￥</i> ${arr.price}</span>
                            <span><i>￥</i> ${arr.delPrice}</span>
                        </div>
                    </a>
                </li>
                `
        });
        $('.long-slideshow ul').html(str);
        let num = 1;
        let flag = true;
        //! clone li
        let arr = $('.long-slideshow ul li').eq(4).prevAll().clone().get().reverse();
        $(arr).appendTo('.long-slideshow ul');
        //! 右按钮
        $('.long-slideshow>button:eq(1)').on('click', () => {
            if (flag) {
                flag = false
                if (num == 4) {
                    $('.long-slideshow ul').css('left', 0)
                    num = 1
                }
                $('.long-slideshow ul').animate({
                    left: -800 * num
                }, 500, 'swing', () => {
                    flag = true
                    num++
                })
            }
        });
        //! 左按钮
        $('.long-slideshow>button:eq(0)').on('click', () => {
            if (flag) {
                flag = false
                if (num == 1) {
                    $('.long-slideshow ul').css('left', -2400)
                    num = 4
                }
                num--
                $('.long-slideshow ul').animate({
                    left: -800 * (num - 1)
                }, 500, 'swing', () => {
                    flag = true
                })
            }
        });
    }

    // ! 特价
    discounts()

    function discounts() {
        // ? 大图
        discountsBig()

        function discountsBig() {
            let discountsBig_data = [{
                    img: "1-10.webp",
                    pname: '良布抽纸 本色无漂白竹浆纸 3层100抽18包整箱 食品级餐巾纸卫生纸巾',
                    price: '19.9',
                    del_price: '49.9',
                },
                {
                    img: "1-20.webp",
                    pname: '香之渝自热红烧肉米饭280g*1盒',
                    price: '13.0',
                    del_price: '29.9',
                },
                {
                    img: "1-30.webp",
                    pname: '年宵花卉银柳彩色银柳鲜枝',
                    price: '14.8',
                    del_price: '25',
                },
                {
                    img: "1-40.webp",
                    pname: '东方宝石沐浴露500ml绿茶焕活',
                    price: '49',
                    del_price: '79',
                }
            ]
            let str = discountsBig_data.map((arr) => {
                return `
                 <div class="le-bd-tbody">
                 <div class="le-bd-box-le">
                 <a href="javascript:;">
                     <img src="../img/special-img/every-img/${arr.img}" alt="">
                     <p>${arr.pname}</p>
                     <span class="red">
                         <span style="color: #e1251b;">￥</span>
                         ${arr.price}
                     </span>
                     <span class="del">
                         <span>￥</span>${arr.del_price}
                     </span>
                 </a>
             </div>
                 <ul></ul>
                 </div>
                 `
            })
            $('<div class="le-bd-tbody-w"></div>').insertAfter('.le-bd-thead').html(str)
            $('.le-bd-tbody').eq(0).addClass('block-bd')
        }
        // ? 小图数据
        let discounts_data = [
            [{
                    img: "1-11.webp",
                    floor: '354天最低价',
                    message_name: '男士祛痘补水面膜清洁面膜',
                    price: '47',
                    del_price: '68',
                    loot: '已抢<span>120</span>件'
                },
                {
                    img: "1-12.webp",
                    floor: '354天最低价',
                    message_name: '精品5棵多肉含盆送土',
                    price: '9.9',
                    del_price: '14.8',
                    loot: ''
                },
                {
                    img: "1-13.webp",
                    floor: '77天最低价',
                    message_name: '采柔儿家用抽纸L号300张×10包',
                    price: '9.9',
                    del_price: '15.9',
                    loot: '已抢<span>256</span>件'
                },
                {
                    img: "1-14.webp",
                    floor: '261天最低价',
                    message_name: '53度500ML 6瓶酱香型白酒',
                    price: '23',
                    del_price: '38',
                    loot: ''
                }
            ],
            [{
                    img: "1-21.webp",
                    floor: '258天最低价',
                    message_name: '坚果干果礼盒年货送礼团购',
                    price: '39.9',
                    del_price: '89',
                    loot: '已抢<span>380</span>件'
                },
                {
                    img: "1-22.webp",
                    floor: '',
                    message_name: '秒抢！5斤仅14.9 盐渍海带丝',
                    price: '14.9',
                    del_price: '30',
                    loot: '已抢<span>187</span>件'
                },
                {
                    img: "1-23.webp",
                    floor: '68天最低价',
                    message_name: '四川不知火丑橘5斤装',
                    price: '19.9',
                    del_price: '29.9',
                    loot: '已抢<span>140</span>件'
                },
                {
                    img: "1-24.webp",
                    floor: '73天最低价',
                    message_name: '昆明冠生园鲜花饼250g盒装',
                    price: '39.85',
                    del_price: '49.9',
                    loot: '已抢<span>169</span>件'
                }
            ],
            [{
                    img: "1-31.webp",
                    floor: '261天最低价',
                    message_name: '变形玩具合金模型大黄蜂',
                    price: '25.6',
                    del_price: '36.8',
                    loot: '已抢<span>152</span>件'
                },
                {
                    img: "1-32.webp",
                    floor: '53天最低价',
                    message_name: '双枪心选禾木天香木福筷',
                    price: '14.5',
                    del_price: '25',
                    loot: '已抢<span>112</span>件'
                },
                {
                    img: "1-33.webp",
                    floor: '259天最低价',
                    message_name: '天气瓶风暴瓶创意礼品摆件',
                    price: '19.8',
                    del_price: '42.9',
                    loot: '已抢<span>256</span>件'
                },
                {
                    img: "1-34.webp",
                    floor: '258天最低价',
                    message_name: '浴室清洁剂洗漱台玻璃清洁剂',
                    price: '49 ',
                    del_price: '99',
                    loot: ''
                }
            ],
            [{
                    img: "1-41.webp",
                    floor: '265天最低价',
                    message_name: '凝胶75%酒精免洗洗手液',
                    price: '49',
                    del_price: '98',
                    loot: ''
                },
                {
                    img: "1-42.webp",
                    floor: '',
                    message_name: '云南本草洁牙慕斯泡沫清新牙膏',
                    price: '33',
                    del_price: '59',
                    loot: ''
                },
                {
                    img: "1-43.webp",
                    floor: '257天最低价',
                    message_name: '韩束护手霜3支装滋润清爽',
                    price: '13.8',
                    del_price: '19.9',
                    loot: '已抢<span>177</span>件'
                },
                {
                    img: "1-44.webp",
                    floor: '261天最低价',
                    message_name: '沐浴阳光控油护理+生姜洗发露',
                    price: '19.9',
                    del_price: '65',
                    loot: '已抢<span>103</span>件'
                }
            ]
        ];
        // ?调用函数
        discounts_data.forEach((v, i) => {
            discountsSmall(v, i)
        });
        // ? 小图函数
        function discountsSmall(discounts_data, num) {
            let str = discounts_data.map((arr) => {
                return `
                 <li>
                 <a href="javascript:;">
                 <div class="img">
                     <img src="../img/special-img/every-img/${arr.img}" alt="">
                     <span>${arr.floor}</span>
                 </div>
                 <div class="message">
                     <span class="message-name">${arr.message_name}</span>
                     <div class="price">
                         <span class="red">
                             <span style="font-size: 12px;">￥</span>${arr.price}
                         </span>
                         <span class="del">￥${arr.del_price}</span>
                     </div>
                     <span class="loot">
                         ${arr.loot}
                     </span>
                 </div>
                 </a>
             </li>`
            })
            $('.le-bd-tbody ul').eq(num).html(str)
        }
        // ? 渲染
        $('.le-bd-tbody ul li a .img span').each((i, v) => {
            if (v.innerHTML == '') {
                $(v).css('display', 'none')
            }
        })
    }
    // ! 特价 tab栏
    discounts_hover()

    function discounts_hover() {
        $('.le-bd-thead ul>li').on('mouseenter', (e) => {
            $('.le-bd-thead ul>li>a').removeClass('bor-bom')
            $(e.target).children().addClass('bor-bom')
            index = $(e.target).index()
            $('.le-bd-tbody').eq(index).addClass('block-bd').siblings().removeClass('block-bd')
        })
    }
    // !跑马灯轮播图
    cyclicSlideshow()

    function cyclicSlideshow() {
        // ! 定时器函数
        timer()

        function timer() {
            time = setInterval(() => {
                let m = parseFloat($('.cyclic-Slideshow ul').css('left'));
                m -= .5;
                $('.cyclic-Slideshow ul').css('left', m);
                $('.scroll span').css('left', -m / 2.23);
                if (parseInt(m) == -1600) {
                    $('.cyclic-Slideshow ul').css('left', 0)
                    num = 0
                }
            }, 10);
        }

        let spanX = 0
        let spanY = 0
            // ! 鼠标 按下
        $('.scroll span').on('mousedown', function(e) {
            let spanX = e.offsetX;
            clearInterval(time);
            // ! 鼠标 移动
            $(document).on('mousemove', fn);

            function fn(e) {
                clearInterval(time);
                // console.log($('.scroll').offset().left);
                let x = e.clientX - $('.scroll').offset().left - spanX;
                $('.scroll span').css('left', x);
                $('.cyclic-Slideshow ul').css('left', -x * 2.32);
                if (x <= 0) {
                    $('.scroll span').css('left', 0)
                    $('.cyclic-Slideshow ul').css('left', 0)
                }
                if (x >= 860) {
                    $('.scroll span').css('left', 860);
                    $('.cyclic-Slideshow ul').css('left', -1600);
                }
            };
            // ! 鼠标 移出
            $(document).on('mouseup', function(e) {
                $(this).off('mousemove', fn)
                clearInterval(time)
            })
        });
        // ! 划过 动画
        $('#nicegoods-wrap').hover(() => {
            clearInterval(time)
            $('.scroll').animate({ opacity: 1 }, 500, 'swing')
        }, () => {
            $('.scroll').animate({ opacity: 0 }, 500, 'swing')
            clearInterval(time)
            timer()
        })

    }

    // ! 列表
    p_list()

    function p_list() {
        let pagesize = 20;
        let uid = localStorage.getItem('id');
        let token = localStorage.getItem('token');
        let params = { uid, pagesize, pagenum }
        axios.get(productListAPI, { params })
            .then((res) => {
                let arr = res.data.data
                if (arr.length == 0) {
                    alert('没有更多了')
                } else {
                    let str = arr.map(v => {
                        return `<li><a href="javascript:;">
                         <div class="p-list-img">
                             <img src="${v['pimg']}" alt="">
                         </div>
                         <div class="p-list-meg">
                             <h1>${v['pname']}</h1>
                             <p>${v['pdesc']}</p>
                             <div class="price">￥<span>${v['pprice']}</span></div>
                             <div class="id"> id:<span>${v['pid']}</span></div>              
                         </div>
                     </a></li> `
                    })
                    $('.p-list-body ul').get()[0].innerHTML += str.join('')
                    detail()
                }
            })
    }

    // ! 跳转详情页
    function detail() {
        $('.p-list-body ul li').on('click', (e) => {
            if (localStorage.getItem('username')) {
                let id = $(e.target).find(' .id span').text()
                params = { id }
                console.log(0000000000);
                axios.get(productDetailAPI, { params })
                    .then(({ data }) => {
                        let xq = JSON.stringify(data.data)
                        console.log(xq);
                        localStorage.setItem('pdetail', xq)
                        location.href = './detail.html'
                    })
            } else {
                // !判断用户是否登录
                alert('请先登录')
                location.href = './login.html'
            }

        })
    }

    // ! 查看购物车
    carList()

    function carList() {
        let id = localStorage.getItem('uid')
        if (id != null) {
            let params = { id }
            let carP_num = 0
            axios.get(cartListAPI, { params })
                .then(({ data }) => {
                    console.log(data);
                    data.data.forEach(v => {
                        carP_num += parseInt(v.pnum)
                    });
                    $('#shopping-cart i').text(carP_num);
                })
            $('#shopping-car').on('click', () => {
                location.href = './shopping-car.html'
            })
        } else {
            $('#shopping-car').on('click', () => {
                location.href = './login.html'
            })
        }

    }
}